#!/usr/bin/python
#coding=utf-8
# Filename: analyze.py
# CreatedBy: ChenZhengguo 2011/12/7

import ConfigParser,urllib,urllib2,string
import msvcrt, sys, os, re
import cPickle
from lxml import etree,html
from lxml.html.clean import Cleaner
from StringIO import StringIO
import mechanize


class ParseAnalyze:
    '''Analyze htmlcode by mechanize, try to recombine the form, generate form_name_map'''
    def __init__(self,id):
        self._error   = {}
        self._htmlDom = None
        self._data = {}
        self._configFile = 'swap\\'+str(id)+'\\form'
        self._config = ConfigParser.ConfigParser()
    def analyze(self,originHtml):  
        cleaner = Cleaner(style=True, links=True, forms = False,
                        page_structure=False, safe_attrs_only=False)
        #print cleaner.clean_html(originHtml)
        h = html.fromstring(originHtml)
        print len(h.forms)
        print h.forms[0].action
        print h.forms[0].inputs
        br = mechanize.Browser()
        #parse = mechanize.ParseHtml(originHtml)
        #print parse.form
        #print h.forms[0].select.value_options
        #print h.forms[0].form_values()
    
    def getFormSerial(self):
        self._config.read(self._configFile)
        print len(self._config.sections()) + 1
    
    def write2Config(self,section,data):
        self._config.add_section(section) 
        
            
    #recombined form
    def form2file(self,id,filename):
        f = open('swap\\'+str(id)+'\\'+filename, 'wb')
        f.write(self._html)
        f.close()
        return True

##test
#a = ParseAnalyze(1)
